package com.backsidecode.service.impl;


import com.backsidecode.common.CustomException;
import com.backsidecode.mapper.UserMapper;
import com.backsidecode.pojo.entity.User;
import com.backsidecode.service.UserService;
import com.backsidecode.utils.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Override
    public String login(String userName, String md5Password) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //比对输入的账号密码在数据库中是否有对应的数据
        queryWrapper.eq(User::getUserName, userName)
                .eq(User::getPassword, md5Password);

        User user = this.getOne(queryWrapper);
        if (user != null) {
            Map<String, Object> claims = new HashMap<>();

            claims.put("id", user.getId());
            claims.put("name", user.getName());
            claims.put("number", user.getUserName());

            String jwt = JwtUtils.generateJwt(claims);
            String token = "Bearea" + " " + jwt;
            log.info(token);
            //将生成的令牌返回 后续前端的每次请求都必须携带这个令牌
            return token;
        }
        throw new CustomException("用户名或密码错误");

    }
}




